/* eslint-disable no-unused-vars */

// 非严格模式下，一共执行三次，严格模式下会执行三次以上

// ErrorBoundary 要自己实现

import { Component } from "react";
import PropTypes from "prop-types";
const getMessage = Promise.reject("errorMsg");
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    //初始化状态
    this.state = {
      hasError: false,
      error: null,
    };
  }
  //静态方法，用于从错误中派生出新的状态
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  render() {
    if (this.state.hasError) {
      return <div>出错被我捕获到了:{this.state.error}</div>;
    }
    //否则直接渲染子组件
    return this.props.children;
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.node.isRequired,
};
function Message() {
  //使用use这个hook处理Promise并获取Promise的值
  const data = use(getMessage);
  return <div>{data}</div>;
}

// 非严格模式下，一共执行三次
function App() {
  console.log("App render");
  return (
    <ErrorBoundary>
      <Message />
    </ErrorBoundary>
  );
}

function use(promise) {
  console.log("use");
  //根据promise的状态进行不同处理
  switch (promise.status) {
    case "fulfilled":
      //如果Promise已经完成，则返回结果
      return promise.value;
    case "rejected":
      //如果Promise已经拒绝，抛出错误
      throw promise.reason;
    default:
      throw promise.then(
        (value) => {
          //成功回调，设置状态为完成，并且保存结果
          promise.status = "fulfilled";
          promise.value = value;
        },
        (reason) => {
          //失败回调，设置状态为拒绝，并且保存错误的原因
          promise.status = "rejected";
          promise.reason = reason;
        }
      );
  }
}
export default App;
//Consider adding an error boundary to your tree to customize error handling behavior.
